<template>
	<EmpireModal v-model="modelValue" title="选择地址">
		<scroll-view class="empire-address__body" :scroll-y="true" :show-scrollbar="false">
			<view class="address-body__content">
				<AddressCard
					v-for="(item, key) in addressSelections"
					:key="key"
					v-model:checked="item.checked"
					v-model:address="item.address"
					:title="item.name"
					:telephone="item.telephone"
					@change="(value) => handleAddressChange(value, item.uid)"
				/>
			</view>
		</scroll-view>
		<view id="button" class="address-pupop__button">
			<button type="warn" @click="handlePlusAddress">新增地址</button>
		</view>
	</EmpireModal>
</template>

<script setup>
import EmpireModal from '@/components/empire-modal.vue';
import AddressCard from '@/components/address/address-card.vue';
import { ref, toRefs, onMounted } from 'vue';
import { useAppStore } from '@/store/store.js';

const store = useAppStore();
const emits = defineEmits(['change']);

const modelValue = defineModel('modelValue', {
	type: Boolean,
	default: false
});
const { address: addressSelections } = toRefs(store);
const pupopHeight = ref();
onMounted(() => {
	const { windowHeight } = uni.getWindowInfo();
	pupopHeight.value = `${windowHeight - 44 - 106}px`;
});

function handleAddressChange(value, id) {
	let address;
	if (value) {
		address = addressSelections.value.find((item) => item.uid === id)?.address;
		const selection = addressSelections.value.map((item) => {
			return {
				...item,
				checked: item.uid === id ? value : !value
			};
		});
		store.set('address', selection);
	}
	emits('change', address);
}

function handlePlusAddress() {}
</script>

<style lang="scss" scoped>
.empire-address__body {
	height: v-bind(pupopHeight);
	margin-bottom: 44px;
}
.address-body__content {
	margin-bottom: 44px;
}
.address-pupop__button {
	position: fixed;
	width: calc(100% - 60rpx);
	bottom: 0;
	margin: 30rpx;
}
</style>
